package com.commerce.user.controller;

import com.commerce.common.utils.Result;
import com.commerce.user.entity.Permission;
import com.commerce.user.entity.Role;
import com.commerce.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/roles")
@CrossOrigin
public class RoleController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户角色列表
     */
    @GetMapping("/user/{userId}")
    public Result<List<Role>> getUserRoles(@PathVariable Long userId) {
        try {
            List<Role> roles = userService.getUserRoleList(userId);
            return Result.success(roles);
        } catch (Exception e) {
            log.error("获取用户角色失败", e);
            return Result.error("获取用户角色失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户权限列表
     */
    @GetMapping("/permissions/user/{userId}")
    public Result<List<Permission>> getUserPermissions(@PathVariable Long userId) {
        try {
            List<Permission> permissions = userService.getUserPermissionList(userId);
            return Result.success(permissions);
        } catch (Exception e) {
            log.error("获取用户权限失败", e);
            return Result.error("获取用户权限失败: " + e.getMessage());
        }
    }

    /**
     * 分配用户角色
     */
    @PostMapping("/assign")
    public Result<Boolean> assignUserRoles(@RequestBody Map<String, Object> params) {
        try {
            Long userId = Long.valueOf(params.get("userId").toString());
            @SuppressWarnings("unchecked")
            List<Long> roleIds = (List<Long>) params.get("roleIds");
            
            boolean result = userService.assignUserRole(userId, roleIds);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分配用户角色失败", e);
            return Result.error("分配用户角色失败: " + e.getMessage());
        }
    }
} 